import { useState } from 'react';
import { Toast } from '@ant-design/react-native';
import { loginApi, saveToken, getCurrentBaseUrl, updateBaseUrl } from './api';
import { LoginScreenProps } from './types';

export const useLoginScreen = ({ onNavigateToDetail }: LoginScreenProps) => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [settingsVisible, setSettingsVisible] = useState(false);
    const [settingsInput, setSettingsInput] = useState('');

    const handleLogin = async () => {
        if (username.trim() && password.trim()) {
            try {
                const res = await loginApi(username, password);
                if (res && res.code === 200) {
                    if (res.data && res.data.token) {
                        await saveToken(res.data.token);
                    }
                    Toast.success(res.msg, 1);
                    setTimeout(() => {
                        onNavigateToDetail();
                    }, 500);
                } else {
                    Toast.fail(res.msg || '用户名或密码错误', 1);
                }
            } catch (e: any) {
                Toast.fail(e.message || '网络错误', 1);
            }
        } else {
            Toast.info('请输入用户名和密码', 1);
        }
    };

    const handleSettingsPress = async () => {
        try {
            const displayUrl = await getCurrentBaseUrl();
            setSettingsInput(displayUrl);
            setSettingsVisible(true);
        } catch (error) {
            console.log('获取当前服务器地址失败:', error);
            setSettingsVisible(true);
        }
    };

    const handleSettingsConfirm = async () => {
        try {
            await updateBaseUrl(settingsInput);
            Toast.success('服务器地址已保存', 1);
            setSettingsVisible(false);
            setSettingsInput('');
        } catch (error: any) {
            Toast.fail(error.message || '保存失败，请重试', 1);
        }
    };

    const handleSettingsCancel = () => {
        setSettingsVisible(false);
        setSettingsInput('');
    };

    return {
        username,
        setUsername,
        password,
        setPassword,
        settingsVisible,
        settingsInput,
        setSettingsInput,
        handleLogin,
        handleSettingsPress,
        handleSettingsConfirm,
        handleSettingsCancel,
    };
}; 